package org.example.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.apache.ibatis.annotations.Mapper;
import org.example.mapper.GoodsMapper;
import org.example.mapper.VendorMapper;
import org.example.pojo.Goods;
import org.example.pojo.PageBean;
import org.example.pojo.Vendor;
import org.example.service.VendorService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

@Service
public class VendorServiceImpl implements VendorService {
    @Autowired
    private VendorMapper vendorMapper;
    @Autowired
    private GoodsMapper goodsMapper;
    /**
     * 查询供应商列表
     * @return
     */
    @Override
    public List<Vendor> list() {
        return vendorMapper.list();
    }

    /**
     * 分页查询供应商列表
     * @param pageNum
     * @param pageSize
     * @param vendorName
     * @return
     */
    @Override
    public PageBean<Vendor> listPage(int pageNum, int pageSize, String vendorName) {
        PageHelper.startPage(pageNum,pageSize);
        Page<Vendor> page = vendorMapper.listPage(vendorName);
        return new PageBean<>(page.getTotal(),page.getResult());
    }

    /**
     * 添加供应商
     * @param vendor
     */
    @Override
    public void add(Vendor vendor) {
        vendor.setCreateTime(LocalDateTime.now());
        vendor.setUpdateTime(LocalDateTime.now());
        vendorMapper.add(vendor);
    }

    /**
     * 修改供应商
     * @param vendor
     */
    @Override
    public void update(Vendor vendor) {
        vendor.setUpdateTime(LocalDateTime.now());
        vendorMapper.update(vendor);
    }

    /**
     * 删除供应商
     * @param id
     */
    @Override
    public void delete(Integer id) {
        // 查询供应商是否关联其他属性，如果关联了就抛出业务异常
        List<Goods> goods = goodsMapper.listByVendorId(id);
        if (!goods.isEmpty()) {
            throw new RuntimeException("当前供应商关联了商品，不能删除");
        }
        // 删除供应商数据
        vendorMapper.delete(id);
    }

    /**
     * 批量删除供应商
     * @param ids
     */
    @Override
    public void batchDelete(List<Integer> ids) {
       for (Integer id : ids){
           vendorMapper.delete(id);
       }
    }

}
